﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RBAC.MaHaiBo.Repository;
using RBAC.MaHaiBo.Repository.Impl;
using RBAC.MaHaiBo.Repository.Interface;
using RBAC.MaHaiBo.Service;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using RBAC.MaHaiBo.Service.TraceabilityService;
using RBAC.MaHaiBo.Repository.Interface.TraceabilityInterface;
using RBAC.MaHaiBo.Repository.Impl.TraceabilityImpl;
using Microsoft.Extensions.Hosting;

namespace RBAC.MaHaiBo.API.Extensions
{
    /// <summary>
    /// 静态类
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static int Toint(this string para)
        {
            int result = 0;

            if (int.TryParse(para, out result))
            {
                return result;
            }
            else
            {
                return -253435;

            }
        }

        public static string Todata(this string para)
        {
            string list = "";

            if (para.Length == 18)
            {
                list = para.Substring(6, 8);
                list = "" + list.Substring(0, 4) + "年" + list.Substring(4, 2) + "月" + list.Substring(6, 2) + "日";
            }
            else
            {
                list = "身份证号码不对";
            }

            return list;
        }

        /// <summary>
        /// 扩展方法（仓储与服务）
        /// </summary>
        /// <param name="services">扩展的值</param>
        /// <returns></returns>
        public static IServiceCollection AddService(this IServiceCollection services)
        {
            //用户
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IUserRepository, UserRepository>();
            //省
            services.AddScoped<IProvinceService, ProvinceService>();
            services.AddScoped<IProvinceRepository, ProvinceRepository>();
            //县
            services.AddScoped<ICountyService, CountyService>();
            services.AddScoped<ICountyRepository, CountyRepository>();
            //市
            services.AddScoped<ICityService, CityService>();
            services.AddScoped<ICityRepository, CityRepository>();
            //角色
            services.AddScoped<IRoleService, RoleService>();
            services.AddScoped<IRoleRepository, RoleRepository>();
            //用户与角色关联
            services.AddScoped<IUserRoleService, UserRoleService>();
            services.AddScoped<IUserRoleRepository, UserRoleRepository>();

            //菜单
            services.AddScoped<IMenuService, MenuService>();
            services.AddScoped<IMenuRepository, MenuRepository>();
            //菜单与角色关联
            services.AddScoped<IMenuRoleRepository, MenuRoleRepository>();
            services.AddScoped<IMenuRoleService, MenuRoleService>();
            //请假申请
            services.AddScoped<ILeaveRepository, LeaveRepository>();
            services.AddScoped<ILeaveService, LeaveService>();

            //溯源
            services.AddScoped<ITracingRepository, TracingRepository>();
            services.AddScoped<ICommodityRepository, CommodityRepository>();
            services.AddScoped<ITracingService, TracingService>();
            //图片
            services.AddScoped<IPlotInfoService, PlotInfoService>();
            services.AddScoped<IPlotInfoRepository, PlotInfoRepository>();
            //养殖
            services.AddScoped<IFarmService, FarmService>();
            services.AddScoped<IFarmRepository, FarmRepository>();
            //保健
            services.AddScoped<IHygieneRepository, HygieneRepository>();
            //企业
            services.AddScoped<IFirmRepository, FirmRepository>();
            //屠宰
            services.AddScoped<ISlaughterService, SlaughterService>();
            services.AddScoped<ISlaughterRepository, SlaughterRepository>();
            //深加工
            services.AddScoped<IDeepProcessingService, DeepProcessingService>();
            services.AddScoped<IDeepProcessingRepository, DeepProcessingRepository>();
            //原材
            services.AddScoped<IRawMaterialRepository, RawMaterialRepository>();
            //辅材
            services.AddScoped<IAccessoriesRepository, AccessoriesRepository>();
            //添加剂
            services.AddScoped<IAdditiveRepository, AdditiveRepository>();
            //包材
            services.AddScoped<IPackingMaterialsRepository, PackingMaterialsRepository>();


            return services;
        }
        /// <summary>
        /// 注入上下文
        /// </summary>
        /// <typeparam name="TDbCountex">上下文</typeparam>
        /// <param name="services">仓储与服务</param>
        /// <param name="connctionString"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbCountex>(this IServiceCollection services, string? connctionString, bool enableSqlLog) where TDbCountex : DbContext
        {
            return services.AddDbContext<TDbCountex>(o =>
            {
                o.UseSqlServer(connctionString, a =>
                {
                    a.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                }).EnableSensitiveDataLogging();

                if (enableSqlLog)
                {
                    o.UseLoggerFactory(LoggerFactory.Create(c =>
                    {
                        c.AddFilter((category, level) => category == DbLoggerCategory.Database.Connection.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }
        /// <summary>
        /// 配置JWT
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builder"></param>
        public static  void AddJwT(this IServiceCollection services ,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                o.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer=true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }


    }
}
